package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.company.Company;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list", name = "查询所有购销合同数据")
    public String findAll(@RequestParam(defaultValue = "1", name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
//        查询购销合同的要求是：1、本企业下的数据  2、排序 根据创建时间

        ContractExample example = new ContractExample();
        //查询的购销合同 select * from co_contract where company_id=? and  create_by=? order by create_time desc
        ContractExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());
        example.setOrderByClause("create_time desc");
        //获取当前登录人
        User user = getUser();
        // 1-企业管理员
        // 2-管理所有下属部门和人员
        // 3-管理本部门
        // 4-普通员工
        Integer degree = user.getDegree();
        if (degree == 4) {
            criteria.andCreateByEqualTo(user.getId());
        } else if (degree == 3) {
            criteria.andCreateDeptEqualTo(user.getDeptId());
        } else if (degree == 2) {
            criteria.andCreateDeptLike(user.getDeptId() + "%");
        }
        PageInfo<Contract> pageBean = contractService.findAll(example, pageNum, pageSize);
        request.setAttribute("page", pageBean);
        return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd", name = "进入新增购销合同页面")
    public String toAdd() {
        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/toUpdate", name = "进入编辑购销合同页面")
    public String toUpdate(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-add";
    }


    @RequestMapping(value = "/edit", name = "保存购销合同方法")
    public String edit(Contract contract) {
        if (StringUtils.isEmpty(contract.getId())) {//ID为空表示新增
            //1、id  2、企业id和企业名称 3、创建时间 4、状态
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setState(0);  ////状态：0草稿 1已上报待报运	2 已报运
            contract.setCreateTime(new Date());
            User user = getUser();
            contract.setCreateBy(user.getId()); //当前登录人
            contract.setCreateDept(user.getDeptId());  //当前登录人的部门id
            contractService.save(contract);
        } else {
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    //提交
    @RequestMapping(value = "/submit")
    public String submit(String id) {
        //将合同状态改为1
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    //取消
    @RequestMapping(value = "/cancel")
    public String cancel(String id) {
        //将合同状态改为0
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/delete")
    public String delete(String id) {
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/print", name = "进入到导出出货表页面")
    public String print() {
        return "cargo/print/contract-print";
    }

    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/printExcel", name = "导出出货表数据")
    public void printExcel(String inputDate) throws Exception {
        //导出一个excel
        //创建了一个里面什么都没有的工作薄
        Workbook workbook = new XSSFWorkbook();
        //创建新的工作表sheet
        Sheet sheet = workbook.createSheet("出货表");
        //设置sheet的列宽
        sheet.setColumnWidth(0, 4200);
        sheet.setColumnWidth(1, 26 * 256);
        sheet.setColumnWidth(2, 16 * 256);
        sheet.setColumnWidth(3, 26 * 256);
        sheet.setColumnWidth(4, 16 * 256);
        sheet.setColumnWidth(5, 16 * 256);
        sheet.setColumnWidth(6, 16 * 256);
        sheet.setColumnWidth(7, 16 * 256);
        sheet.setColumnWidth(8, 16 * 256);
        Row bigTitleRow = sheet.createRow(0);
        //设置行高
        bigTitleRow.setHeightInPoints(36);  //设置行高
        Cell cell = null;
        for (int i = 1; i <= 8; i++) {
            cell = bigTitleRow.createCell(i);
            cell.setCellStyle(bigTitle(workbook));
        }
        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        //向合并后的单元格中写入一句话：2012年8月份出货表
        bigTitleRow.getCell(1).setCellValue(inputDate.replaceAll("-0", "年").replaceAll("-", "年") + "月份出货表");        //处理小标题行
        Row titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(26);
        String[] tiltes = new String[]{"客户", "合同号", "货号", "数量", "工厂", "工厂交期", "船期", "贸易条款"};
        for (int i = 1; i <= 8; i++) {
            cell = titleRow.createCell(i);
            cell.setCellValue(tiltes[i - 1]);
            cell.setCellStyle(title(workbook));
        }
        //处理内容
        //查询需要导出的数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate, getCompanyId());
        int rowIndex = 2;
        Row row = null;
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(rowIndex);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(text(workbook));
//            工厂	工厂交期	船期	贸易条款
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(text(workbook));
            rowIndex++;
        }
//        把excel导出  1、字节缓存流 2、相应  3、文件的名称
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream, response, "出货表.xlsx");
    }

    @RequestMapping(value = "/printExcelWithTemplate", name = "导出出货表使用模板")
    public void printExcelWithTemplate(String inputDate) throws Exception {
        String templatePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templatePath));
        //导出一个excel
        //创建了一个里面什么都没有的工作薄
        //创建新的工作表sheet
        Sheet sheet = workbook.getSheetAt(0);
        sheet.getRow(0).getCell(1).setCellValue(inputDate.replaceAll("-0", "年").replace("-", "年") + "月份出货表");
        //处理内容
        //查询需要导出的数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate, getCompanyId());
        int rowIndex = 2;
        Row row = null;
        Cell cell = null;
        //获取模板中主体内容的单元格样式
        CellStyle[] cellStyles = new CellStyle[8];
        row = sheet.getRow(2);
        for (int i = 1; i <= 8; i++) {
            cellStyles[i-1] = row.getCell(i).getCellStyle();
        }
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(rowIndex);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(cellStyles[0]);

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(cellStyles[3]);
//            工厂	工厂交期	船期	贸易条款
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(cellStyles[7]);
            rowIndex++;
        }
//        把excel导出  1、字节缓存流 2、相应  3、文件的名称
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream, response, "出货表.xlsx");
    }

    //大标题的样式
    public CellStyle bigTitle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);                //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线

        return style;
    }
}
